<?php
/**
 * Tags url rewrite resource model
 *
 * @category    Ddup
 * @package     Ddup_Catalog
 * @author      Aaron
 */
class Ddup_Tags_Model_Resource_Url extends Mage_Core_Model_Resource_Db_Abstract
{
	/**
     * Load core Url rewrite model
     *
     */
    protected function _construct()
    {
        $this->_init('core/url_rewrite', 'url_rewrite_id');
    }
    
	/**
     * Retrieve stores array or store model
     *
     * @param int $storeId
     * @return Mage_Core_Model_Store|array
     */
    public function getStores($storeId = null)
    {
        if ($this->_stores === null) {
            $this->_stores = Mage::app()->getStores();
        }
        if ($storeId && isset($this->_stores[$storeId])) {
            return $this->_stores[$storeId];
        }
        return $this->_stores;
    }
    
	/**
     * Retrieve Tag data objects for store
     *
     * @param int $storeId
     * @param int $lastEntityId
     * @return array
     */
    public function getTagsByStore($storeId)
    {
        return $this->_getTags($storeId);
    }
    
	/**
     * Finds and deletes old rewrites for store
     * 
     * @param int $storeId
     * @return Ddup_Tags_Model_Resource_Url
     */
    public function clearStoreTagsInvalidRewrites($storeId, $tagId)
    {
        $tagIds = $this->getTagIds($storeId);
        
        // Remove all store tag rewrites
        $where   = array(
            'store_id = ?' => $storeId,
            'tag_id IS NOT NULL', // For sure check that it's a catalog rewrite
            'tag_id NOT IN (?)' => $tagIds
        );        
        $this->_getWriteAdapter()->delete($this->getMainTable(), $where);
        
        return $this;
    }
    
    /**
     * Retrieves all Tag ids of the store
     * 
     * @param int $storeId
     * @return Varien_Object
     */
    public function getTagIds($storeId)
    {
    	$adapter = $this->_getReadAdapter();
    	$select = $adapter->select()
            ->from(array('tag' => $this->getTable('tag/relation')), 'tag_id')
            ->where('tag.store_id = ?',$storeId);
    	$rowSet = $adapter->fetchAll($select);
        foreach ($rowSet as $row) {
            $tagIds[$row['tag_id']] = $row['tag_id'];
        }
        return $tagIds;
    }
    
	/**
     * Retrieve Tag data objects
     *
     * @param int|array $productIds
     * @param int $storeId
     * @param int $entityId
     * @param int $lastEntityId
     * @return array
     */
    protected function _getTags($storeId)
    {
        $tagCollection = Mage::getResourceModel('tag/tag_collection')
        				->addStoreFilter($storeId);
        return $tagCollection;
    }
    
	/**
     * Prepare tags rewrites for condition
     *
     * @param int $storeId
     * @param int|array $categoryIds
     * @param int|array $productIds
     * @return array
     */
    public function prepareTagsRewrites($storeId, $tagIds = null)
    {
        $rewrites   = array();
        $adapter    = $this->_getReadAdapter();
        $select     = $adapter->select()
            ->from($this->getMainTable())
            ->where('store_id = :store_id')
            ->where('is_system = ?', 0);
            
        $bind = array('store_id' => $storeId);        
        $select->where('tag_id IN(?)', $tagIds);
        $rowSet = $adapter->fetchAll($select, $bind);

        foreach ($rowSet as $row) {
            $rewrite = new Varien_Object($row);
            $rewrite->setIdFieldName($this->getIdFieldName());
            $rewrites[$rewrite->getIdPath()] = $rewrite;
        }

        return $rewrites;
    }
    
	/**
     * Save rewrite URL
     *
     * @param array $rewriteData
     * @param int|Varien_Object $rewrite
     * @return Mage_Catalog_Model_Resource_Url
     */
    public function saveRewrite($rewriteData, $rewrite)
    {
        $adapter = $this->_getWriteAdapter();
        if ($rewrite && $rewrite->getId()) {
            if ($rewriteData['request_path'] != $rewrite->getRequestPath()) {
                $where = array($this->getIdFieldName() . '=?' => $rewrite->getId());
                $adapter->update($this->getMainTable(), $rewriteData, $where);

                // Update existing rewrites history and avoid chain redirects
                $where = array('target_path = ?' => $rewrite->getRequestPath());
                if ($rewrite->getStoreId()) {
                    $where['store_id = ?'] = (int)$rewrite->getStoreId();
                }
                $adapter->update(
                    $this->getMainTable(),
                    array('target_path' => $rewriteData['request_path']),
                    $where
                );
            }
        } else {
            try {
                $adapter->insert($this->getMainTable(), $rewriteData);
            } catch (Exception $e) {
                Mage::logException($e);
                Mage::throwException(Mage::helper('core')->__('An error occurred while saving the tag URL rewrite'));
            }
        }
        unset($rewriteData);

        return $this;
    }
    
	public function getRewriteByIdPath($idPath, $storeId)
    {
        $adapter = $this->_getReadAdapter();
        $select = $adapter->select()
            ->from($this->getMainTable())
            ->where('store_id = :store_id')
            ->where('id_path = :id_path');
        $bind = array(
            'store_id' => (int)$storeId,
            'id_path'  => $idPath
        );
        
        $row = $adapter->fetchRow($select, $bind);

        if (!$row) {
            return false;
        }
        $rewrite = new Varien_Object($row);
        $rewrite->setIdFieldName($this->getIdFieldName());

        return $rewrite;
    }
    
	/**
     * Retrieve rewrite by requestPath
     *
     * @param string $requestPath
     * @param int $storeId
     * @return Varien_Object|false
     */
    public function getTagRewriteByRequestPath($requestPath, $storeId)
    {
        $adapter = $this->_getWriteAdapter();
        $select = $adapter->select()
            ->from($this->getMainTable())
            ->where('store_id = :store_id')
            ->where('request_path = :request_path');
        $bind = array(
            'request_path'  => $requestPath,
            'store_id'      => (int)$storeId
        );
        $row = $adapter->fetchRow($select, $bind);

        if (!$row) {
            return false;
        }
        $rewrite = new Varien_Object($row);
        $rewrite->setIdFieldName($this->getIdFieldName());

        return $rewrite;
    }
}
